package com.iweb.day12;

/**
 * @author WuYongheng
 * @date 2021/12/5
 * @description 模拟火车站抢票，请看门大爷帮忙上锁
 */
public class TicketDemo2 implements Runnable {
    // 共享数据，票数信息
    private int count = 10;
    // 当前卖出的票数
    private int num = 0;
    // final 的意义，要求看门的人不能变
    private final Object OldMan = new Object();


    @Override
    public void run() {
        while (true) {
            // 加上合理的延时，给其他线程机会
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 请看门大爷帮忙上锁
            synchronized (OldMan) {
                // 一直卖票知道卖完为止
                if (count <= 0) {
                    break;
                }
                // 模拟买票，卖的票数增加，剩余的票数减少
                count--;
                num++;
                // 模拟网络延时
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 显示售票信息
                System.out.println(Thread.currentThread().getName()
                        + "抢到第" + num + "张票，剩余" + count + "张票！");
            }
        }
    }

    public static void main(String[] args) {
        TicketDemo2 ticketDemo = new TicketDemo2();
        // 开启多个子线程
        Thread t1 = new Thread(ticketDemo);
        Thread t2 = new Thread(ticketDemo);
        Thread t3 = new Thread(ticketDemo);

        t1.setName("张三");
        t2.setName("代理");
        t3.setName("黄牛党");

        System.out.println("开始抢票啦！");

        t1.start();
        t2.start();
        t3.start();
    }
}
